<template>
  <div class="student_allocation">
    <div class="common_bg" v-if="studentList.length !== 0"></div>
    <div v-if="studentList.length == 0" class="noData">
      <img src="../../../assets/img/nodata.png" alt="">
      <p>暂时还没有数据</p>
      <p>请先添加学员</p>
      <span class="addData" @click="addStudentAllocation">添加</span>
    </div>
    <div class="student_allocation_container" v-if="studentList.length !== 0">
      <div class="student_number">
        <span>待分配学员</span>
        <span class="number">{{studentList.length}}</span>
      </div>

      <div class="student_list">
        <van-checkbox-group v-model="checkStudentList">
          <van-cell-group>
            <van-cell
              v-for="(item, index) in studentList"
              clickable
              :key="index"
              @click="toggle('checkboxes',index)"
            >
              <span class="student_info">{{item.studentName}}</span>
              <span class="student_info">{{item.linkPhone}}</span>
              <span class="student_info">{{item.linkPerson}}</span>
              <van-checkbox
                :name="item"
                ref="checkboxes"
                slot="right-icon"
              />
            </van-cell>
          </van-cell-group>
        </van-checkbox-group>
      </div>

      <div class="allocation_btn_box">
        <span class="ckeck_num">已选中<span class="num">{{checkStudentList.length}}</span>项</span>
        <van-button @click="btnAllocation" color="#FC8434" size="small" round plain>分配</van-button>
      </div>
    </div>

    <div class="icon_place" @click="screenList.showSearch = true"></div>


    <!-- 弹窗层 -->
      <div class="popup">
        <van-popup v-model="showBottomArea" position="bottom" :style="{ height: '40%' }">
          <van-datetime-picker
            v-if="showBottomAreaType == 'date'"
            v-model="currentDate"
            type="date"
            @cancel="onCancel"
            @confirm="onConfirm"
          />

          <van-picker
            v-else
            show-toolbar
            title="请选择"
            value-key="label"
            :columns="bottomAreaList"
            @cancel="onCancel"
            @confirm="onConfirm"
          />
        </van-popup>
      </div>

      <screen :screenList="screenList" @reset="reset" :screenData="screenData" @searchData="searchData" @schoolChange="schoolChange"></screen>

      <!-- 分配弹窗 -->
        <van-popup v-model="showAllocationPage" class="" position="right" :style="{ height: '100%', width: '100%', background: '#F7F9FF' }">
          <div class="top_bar pop_top_bar">
            <span class="icon_left" @click="hideAllocationPage"></span> 
            <span class="title">分配至</span> 
            <span @click="save">完成</span>
          </div>
          <div class="common_bg"></div>
          <div class="student_allocation_container">
            <van-cell :value="salePersonName" is-link @click="handleShowBottomArea('salePerson')">
              <template slot="title">
                <span class="custom-title">课程顾问</span>
              </template>
            </van-cell>

            <div class="student_list" style="margin-top: 20px;">
              <van-checkbox-group v-model="checkStudentListDouble">
                <van-cell-group>
                  <van-cell
                    v-for="(item, index) in checkStudentList"
                    clickable
                    :key="index"
                    @click="toggle('checkboxesDouble', index)"
                  >
                    <span class="student_info">{{item.studentName}}</span>
                    <span class="student_info">{{item.linkPhone}}</span>
                    <span class="student_info">{{item.linkPerson}}</span>
                    <van-checkbox
                      :name="item"
                      ref="checkboxesDouble"
                      slot="right-icon"
                    />
                  </van-cell>
                </van-cell-group>
              </van-checkbox-group>
            </div>
          </div>
        </van-popup>

      <!-- 分配弹窗 -->
    <!-- 弹窗层 -->

  </div>
</template>

<style>
.student_allocation .student_list .van-cell-group{
  background: transparent;
}
.student_allocation .student_list .van-cell{
  margin-bottom: .133333rem;
  padding: .4rem .426667rem;
}
</style>
<style scoped>

.student_allocation .common_bg {
  height: 1.673333rem;
}
.student_allocation_container {
  position: relative;
  padding-top: .746667rem;
}

.student_allocation .van-cell {
  padding: 15px 16px;
}



.student_allocation .allocation_btn_box {
  height: 1.333333rem;
  background:linear-gradient(236deg,rgba(255,152,83,1) 0%,rgba(255,151,151,1) 100%);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 .266667rem;
  box-sizing: border-box;
  margin-top: .533333rem;
  position: sticky;
  width: 100%;
  bottom: 0;
}
.student_allocation .ckeck_num {
  font-size: .373333rem;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
}
.student_allocation .ckeck_num .num {
  color: #E02020;
  width: .56rem;
  height: .56rem;
  display: inline-block;
  background: #fff;
  border-radius: 50%;
  margin: 0 .08rem;
  display: flex;
  justify-content: center;
  align-items: center;
}
.student_allocation .student_list {
  margin-top: .133333rem;
}

.student_allocation .student_info {
  margin-right: .8rem;
}


.student_allocation .student_number{
  display: flex;
  align-items: center;
  padding: 0 .266667rem;
  box-sizing: border-box;
}
.student_allocation .student_number span{
  font-size: .373333rem;
  color: #fff;
}
.student_allocation .student_number .number {
  width: .946667rem;
  height: .32rem;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #77A4FF;
  border-radius: .186667rem;
  font-size: .266667rem;
  margin-left: .133333rem;
}


</style>

<script>
import screen from '../../assembly/screen.vue'
import {
  createNamespacedHelpers
} from "vuex";
let {
  mapState,
  mapGetters,
  mapMutations,
  mapActions
} = createNamespacedHelpers("studentAllocation");


export default {
  name: 'studentAllocation',
  data() {
    return {
      jwtAuth: {},
      showSearch: false,
      showSearchChildren: false,
      showBottomArea: false,
      showAllocationPage: false,

      studentList: [],
      checkStudentList: [],
      checkStudentListDouble: [],
      salePersonName: '请选择',
      salePersonId: '',
      seachSalesPerson: '',
      showBottomAreaType: '',
      activeNames: [],
      salesPersonRadio: '',
      bottomAreaList: [],

      schoolList: [],
      /* 筛选 */
      screenData: {
        school: '',
        schoolId: [],
        contractStatus: '',
        contractStatusId: '',
        saleStatus: '',
        saleStatusId: '',
        product: '',
        productId: [],
        age: '',
        ageId: '',
        parentLabels: '',
        parentLabelsId: '',
        customerSource: '',
        customerSourceId: '',
        salesPerson: '',
        salesPersonId: '',
        noFollowDay: '',
        noFollowDayId: '',
        todayFollowStatus: '',
        todayFollowStatusId: '',
        createStartTime: "",
        createEndTime: "",
      },
      screenList: {
        showSearch: false,
        dateType: 'date',
        minDate: new Date(2019, 0, 1),
        data: [
          {
            label: '校区',
            key: 'school',
            checkType: 'checkbox',
            bottomType: 'list',
            options: [],
          },
          {
            label: '签约状态',
            key: 'contractStatus',
            checkType: 'radio',
            bottomType: 'list',
            options: [],
          },
          {
            label: '销售状态',
            key: 'saleStatus',
            checkType: 'radio',
            bottomType: 'list',
            options: [],
          },
          {
            label: '学员标签',
            key: 'parentLabels',
            checkType: 'radio',
            bottomType: 'list',
            options: [],
          },
          {
            label: '意向课程',
            key: 'product',
            checkType: 'radio',
            bottomType: 'list',
            options: [],
          },
          {
            label: '学员年龄',
            key: 'age',
            checkType: 'radio',
            bottomType: 'list',
            options: [],
          },
          {
            label: '客户来源',
            key: 'customerSource',
            checkType: 'radio',
            bottomType: 'list',
            options: [],
          },
          {
            label: '课程顾问',
            key: 'salesPerson',
            checkType: 'radio',
            bottomType: 'list',
            options: [],
          },
          {
            label: '未跟进天数',
            key: 'noFollowDay',
            checkType: 'radio',
            bottomType: 'timeSection',
            options: [],
          },
          // {
          //   label: '当天跟进状态',
          //   key: 'todayFollowStatus',
          //   checkType: 'radio',
          //   bottomType: 'list',
          //   options: [
          //     {
          //       id: '',
          //       label: '全部'
          //     },
          //     {
          //       id: '10130',
          //       label: '今日待跟进'
          //     },
          //     {
          //       id: '10131',
          //       label: '今日已跟进'
          //     }
          //   ],
          // },
          {
            label: '录入时间-开始',
            key: 'createStartTime',
            checkType: 'date',
            bottomType: 'date',
            options: [],
          },
          {
            label: '录入时间-结束',
            key: 'createEndTime',
            checkType: 'date',
            bottomType: 'date',
            options: [],
          },
          
        ],
      },
      /* end */
      
      activeScreenKey: '',
      bottomType: '',
      currentDate: new Date(),
      currentChildPop: {
        label: '',
      }
    }
  },
  created() {
    this.jwtAuth = JSON.parse(sessionStorage.getItem('jwtAuth'));
    this.queryAllSchool();
    this.queryAllSaleStatus();
    this.queryAllParentLabel();
    this.quertAllCustomerSource();
    this.queryAllAge();
   
  },
  mounted() {
   
  },
  
  methods: {
    ...mapMutations([
      "updateInfo",
    ]),
    ...mapActions([
      "formGet",
      "post"
    ]),

    reset() {
      this.queryAllContractStatus({});
      this.queryAllProduct({});
      this.queryAllSalePerson({});
    },

    searchData(data) {
      console.log(data);
      let searchData = {};
      searchData.schoolId = data.schoolId.length > 0 ? data.schoolId.split(',') : [];
      searchData.signingStatus = data.contractStatusId;
      searchData.salesStatus = data.saleStatusId;
      searchData.labelManagementId = data.parentLabelsId;
      searchData.productId = data.productId.length > 0 ? data.productId.split(',') : [];
      searchData.customerId = data.customerSourceId;
      searchData.personId = data.salesPersonId;
      searchData.daysNotFollowedStart = data.noFollowDay.split('-')[0];
      searchData.daysNotFollowedEnd = data.noFollowDay.split('-')[1] || '';
      searchData.daysNeedFollow = data.todayFollowStatusId;
      searchData.createEndTime = data.createEndTime;
      searchData.createStartTime = data.createStartTime;
      
      if(data.ageId == '40001') {
        searchData.age = '0';
      }else{
        searchData.age = parseInt(data.age);
      }

      this.screenList.showSearch = false;
      this.initData(searchData)
    },

    initData(searchData) {
      let data = {}
      Object.assign(data, searchData);


      if(!data.schoolId || data.schoolId.length == 0) {
        data.schoolId = [];
        this.schoolList.forEach(item => {
          data.schoolId.push(item.schoolId);
        })
      }
      
      // return false;
      this.post({
        API: 'queryStudentForAllocation',
        data: data
      }).then(res => {
        this.studentList = res;
      })
    },

    // 分配
    btnAllocation() {
      if(this.checkStudentList.length == 0) {
        this.$toast.fail('请选择学员');
        return false;
      }
      this.showAllocationPage = true;
      this.salePersonName = '请选择'
      this.salePersonId = ''
      this.checkStudentListDouble = this.checkStudentList.concat();
    },

    save() {
      let data = {
        personDtoList: [
          {
            personId: this.salePersonId,
            personName: this.salePersonName,
            studentDtoList: []
          }
        ]
      }

      data.personDtoList.studentDtoList = [];
      this.checkStudentList.forEach((item) => {
        let obj = {
          studentId: item.studentId
        }
        data.personDtoList[0].studentDtoList.push(obj)
      })
      console.log(data)
      // return false;

      this.post({
        API: 'allocationStudent',
        data: data
      }).then(res => {
        this.$notify({ type: 'success', message: '分配成功',duration: 1000 });
        this.initData();
        this.checkStudentList = [];
        this.showAllocationPage = false;
      }).catch(err => {
        this.$toast.fail(err);
      })
    },

    hideAllocationPage() {
      this.showAllocationPage = false;
      this.checkStudentList = this.checkStudentListDouble.concat();
    },

    handleShowBottomArea(type) {
      this.bottomType = type;
      switch (type) {
        case 'salePerson':
          this.showBottomArea = true;
          this.bottomAreaList = this.salePersonList
          break;
      
        default:
          break;
      }
    },


    clickScreenItem(item, index) {
      this.activeScreenKey = item.key
      switch (item.type) {
        case 1:
          this.showBottomAreaType = ''
          this.bottomAreaList = item.options;
          this.showBottomArea = true;
          break;
        case 2:
          this.currentChildPop.label = item.label;
          this.showSearchChildren = true;
          break;
        case 3:
          this.showBottomAreaType = 'date'
          this.showBottomArea = true;
          break;
      
        default:
          break;
      }
    },

    toggle(ref, index) {
      this.$refs[ref][index].toggle();
      // console.log(index);
    },

    onConfirm(value, index) {
      console.log(`当前值：${value.id || value}, 当前索引：${index}`)
      
      if(this.bottomType == 'salePerson') {
        this.salePersonId = value.id;
        this.salePersonName = this.salePersonList[index].employeesName;
      }

      // this.searchData[this.activeScreenKey] = value;
      this.showBottomArea = false;
    },
    onCancel() {
      this.showBottomArea = false;
    },

    queryAllSchool(btnId) {
      let accountId
      this.jwtAuth.schoolId == '' ? accountId = '' : accountId = this.jwtAuth.accountId
      
      this.post({
        API: 'queryAllSchool',
        data: {
          accountId: accountId,
          menuId: btnId || 'studentManagement',
          schoolIds: this.jwtAuth.schoolId.split(','),
        }
      }).then(res => {
        res = res.filter(val => {
          return val.schoolId !== '';
        });
        res.map((val) => {
          val.label = val.schoolName;
          val.id = val.schoolId;
        })

        this.schoolList = res;
        let schoolId = []
        this.schoolList.map((val) => {
          schoolId.push(val.schoolId);
        })

        let schoolIdStr = schoolId.join(',')

        this.screenList.data.forEach(item => {
          if(item.key == 'school') {
            item.options = this.schoolList;
          }
        })

        this.initData()
        this.queryAllPerson(schoolIdStr);

        let data = {};
        this.queryAllContractStatus(data);
        this.queryAllProduct({});
        this.queryAllSalePerson({});

      }).catch(err => {
        // this.$toast.fail(err);
      })
    },
    queryAllPerson(schoolId) {
      this.formGet({
        API: 'queryPersonBySchoolId',
        data: {
          positionCode: '2,5,15',
          schoolId: schoolId,
        }
      }).then(res => {
        res.map((val) => {
          val.id = val.employeesId;
          val.label = val.employeesName;
        })
        this.salePersonList = res;

      })
    },

    /* ========  筛选组件  =========== */
    schoolChange(data) {
      console.log(data);
      this.queryAllSalePerson(data);
      this.queryAllProduct(data);
      this.queryAllContractStatus(data);
    },

    queryAllContractStatus(data) {
      let schoolIdList = []
      this.schoolList.forEach(item => {
        schoolIdList.push(item.schoolId);
      })
      if(!data.schoolId) {
        data.schoolId = schoolIdList
      }else{
        data.schoolId = [data.schoolId]
      }
      // 查询 签约状态
      this.post({       
        API: 'queryByDicKeyForStudent',
        data: {
          dicKey: 'contractStatus',
          schoolId: data.schoolId,
        }
      }).then(res => {
        res.map((val) => {
          val.id = val.dicCode;
          val.label = val.dicLabel;
        })
        this.screenList.data.forEach(item => {
          if(item.key == 'contractStatus') {
            item.options = res;
          }
        })
      })
    },
    queryAllSaleStatus() {
      // 查询 销售状态
      this.formGet({       
        API: 'queryByDicKey',
        data: {
          dicKey: 'saleStatus',
        }
      }).then(res => {
        res.map((val) => {
          val.id = val.dicCode;
          val.label = val.dicLabel;
        })
        this.screenList.data.forEach(item => {
          if(item.key == 'saleStatus') {
            item.options = res;
          }
        })
      })
    },
    queryAllParentLabel() {
      this.post({
        API: 'selectBmLabelManagementPageList',
        data: {}
      }).then(res => {
        res = res.filter(val => {
          return val.parentId != 0;
        })
        res.map((val) => {
          val.id = val.labelManagementId;
          val.label = val.labelManagementName;
        })
        this.screenList.data.forEach(item => {
          if(item.key == 'parentLabels') {
            item.options = res;
          }
        })
      })
    },
    quertAllCustomerSource() {
      this.post({
        API: 'selectBmCustomerPageList',
        data: {}
      }).then(res => {
        res.map((val) => {
          val.id = val.customerId;
          val.label = val.customerRemark;
        })
        this.screenList.data.forEach(item => {
          if(item.key == 'customerSource') {
            item.options = res;
          }
        })
      })
      
    },
    queryAllSalePerson(data) {
      let schoolIdList = []
      this.schoolList.forEach(item => {
        schoolIdList.push(item.schoolId);
      })

      let schoolId = '';
      if(!data.schoolId) {
        schoolId = schoolIdList.join(',');
      }else{
        schoolId = data.schoolId
      }

      console.log(schoolId)

      this.formGet({
        API: 'queryPersonBySchoolId',
        data: {
          positionCode: '2,5,15',
          schoolId: schoolId,
        }
      }).then(res => {
        res.map((val) => {
          val.id = val.employeesId;
          val.label = val.employeesName;
        })
        this.screenList.data.forEach(item => {
          if(item.key == 'salesPerson') {
            item.options = res;
          }
        })
      }).catch(err => {
        this.$toast.fail(err);
      })
    },
    /** 
    queryAllSchool(btnId) {
      let accountId
      this.jwtAuth.schoolId == '' ? accountId = '' : accountId = this.jwtAuth.accountId
      
      this.post({ 
        API: 'queryAllSchool',
        data: {
          accountId: accountId,
          menuId: btnId || this.$route.name,
          schoolIds: this.jwtAuth.schoolId.split(','),
        }
      }).then(res => {
        res = res.filter(val => {
          return val.schoolId !== '';
        });
        res.map((val) => {
          val.label = val.schoolName;
          val.id = val.schoolId;
        })

        if(btnId) {
          this.powerSchoolList = res
        }else{
          this.schoolList = res
          this.initData();
        }

        this.screenList.data.forEach(item => {
          if(item.key == 'school') {
            item.options = this.schoolList;
          }
        })
      }).catch(err => {
        this.$toast.fail(err);
      })
    },*/
    queryAllProduct(data) {
      let schoolIdList = []
      this.schoolList.forEach(item => {
        schoolIdList.push(item.schoolId);
      })

      let schoolId = '';
      if(!data.schoolId) {
        schoolId = schoolIdList.join(',');
      }else{
        schoolId = data.schoolId
      }

      this.formGet({
        API: 'queryProductBySchoolId',
        data: {
          schoolId: schoolId,
        }
      }).then(res => {
        res.map((val) => {
          val.id = val.productId;
          val.label = val.productName;
        })
        this.screenList.data.forEach(item => {
          if(item.key == 'product') {
            item.options = res;
          }
        })

      }).catch(err => {
        this.$toast.fail(err);
      })
    },
    queryAllAge() {
      this.formGet({       
        API: 'queryByDicKey',
        data: {
          dicKey: 'studentAge',
        }
      }).then(res => {
        res.map((val) => {
          val.id = val.dicCode;
          val.label = val.dicLabel;
        })
        this.screenList.data.forEach(item => {
          if(item.key == 'age') {
            item.options = res;
          }
        })
      })
    },

    addStudentAllocation() {
      this.$router.push({
        name: 'addStudent'
      })
    }

    
    
  },
  computed: {
    ...mapState([
    ]),
   
  },
  components: {
    screen,
  },
}

</script>